package com.example.springboot_10_uploadanddownload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class FileController {
  private static final String dirPath = "D:/Project/maven/File/";
  @GetMapping("/upload")
    public String upLoad(){
      return "upload";
  }
  @PostMapping("/upload")
  public String upLoadFile(@PathVariable(name="files") MultipartFile[] files, Model model){
    for(MultipartFile file : files) {
      if (!file.isEmpty()) {
       String fileName = file.getOriginalFilename();
        File filePath = new File(dirPath);
        if(!filePath.exists()){
          if(!filePath.mkdirs()){
            model.addAttribute("msg","创建目录失败");
            return  "upload";
          }
        }
        File newFile=new File(dirPath+fileName);
        if(newFile.exists()){
          model.addAttribute("msg","已有同名文件存在");
          return  "upload";
        }
        try{
          file.transferTo(newFile);
        } catch (Exception e) {
          model.addAttribute("msg","上传失败"+e.getMessage());
        }
          model.addAttribute("msg","上传成功");
        }
        else
        {
          model.addAttribute("msg","选择文件");
        }
      }
      return "upload";
    }
  }


